package com.chen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chen.dao.mapper.CourseRecordMapper;
import com.chen.dao.pojo.Coach;
import com.chen.dao.pojo.Course;
import com.chen.dao.pojo.CourseRecord;
import com.chen.service.CoachService;
import com.chen.service.CourseRecordService;
import com.chen.service.CourseService;
import com.chen.util.DateUtils;
import com.chen.vo.CourseVo;
import com.chen.vo.Result;
import com.chen.vo.param.RecordParam;
import java.util.LinkedList;
import java.util.List;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author:chenao
 * @DATE:2022/4/1 16:28
 */
@Service
public class CourseRecordServiceImpl implements CourseRecordService {

    @Autowired
    private CourseRecordMapper courseRecordMapper;
    @Autowired
    private CourseService courseService;
    @Autowired
    private CoachService coachService;

    @Override
    public Result insertRecord(CourseRecord courseRecord) {
        if (courseRecord!=null) {
            courseRecordMapper.insert(courseRecord);
        }
        return Result.success("约课成功");
    }

    @Override
    public Boolean isRecord(String userId, String courseId) {
        LambdaQueryWrapper<CourseRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseRecord::getCourseId,courseId);
        wrapper.eq(CourseRecord::getUserId,userId);
        CourseRecord courseRecord = courseRecordMapper.selectOne(wrapper);
        if (courseRecord==null){
            return false;
        }else{
            return true;
        }
    }

    @Override
    public Result getUserRecord(RecordParam param) {
        LambdaQueryWrapper<CourseRecord> wrapper = new LambdaQueryWrapper<>();
        if (Strings.isBlank(param.getUserId())){
            return Result.fail(10000,"参数错误");
        }
        wrapper.eq(CourseRecord::getUserId,param.getUserId());
        List<CourseRecord> courseRecords = courseRecordMapper.selectList(wrapper);
        List<CourseVo> courseVoList=new LinkedList<>();
        courseRecords.stream().forEach(item->{
            Course course = courseService.getCourseById(item.getCourseId());
            CourseVo courseVo = new CourseVo();
            BeanUtils.copyProperties(course,courseVo);
            Coach coach = coachService.findCoachById(course.getCoachId());
            courseVo.setCoachName(coach.getName());
            courseVo.setCoachIntroduce(coach.getIntroduce());
            courseVo.setCoachAuth(coach.getCoachAuth());
            courseVo.setTime(DateUtils.formatCourseTime(course));
            courseVo.setCoachAvatar(coach.getAvatar());
            courseVoList.add(courseVo);
        });
        return Result.success(courseVoList);
    }
}
